﻿using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using VerEasy.Core.Common.Helper;
using VerEasy.Core.Common.Utils;
using VerEasy.Core.Extensions.Caching.Redis;

namespace VerEasy.Core.Extensions.ServiceExtensions
{
    public static class RedisSetup
    {
        public static void AddRedisSetup(this IServiceCollection services)
        {
            if (Appsettings.App("Redis", "Enable").ObjToBool())
            {
                var redisConfig = string.Empty;

                //集群
                if (Appsettings.App("Redis", "UseCluster").ObjToBool())
                {
                    redisConfig = Appsettings.App("Redis", "ConnectionCluster");
                }
                else
                {
                    redisConfig = Appsettings.App("Redis", "ConnectionSingle");
                }

                //注入
                var configurationOptions = ConfigurationOptions.Parse(redisConfig, true);
                configurationOptions.ResolveDns = true;
                var connectionMultiplexer = ConnectionMultiplexer.Connect(configurationOptions);

                services.AddSingleton<IConnectionMultiplexer>(connectionMultiplexer);

                services.AddStackExchangeRedisCache(x =>
                {
                    x.ConnectionMultiplexerFactory = () => Task.FromResult(connectionMultiplexer as IConnectionMultiplexer);
                    if (!string.IsNullOrEmpty(Appsettings.App("Redis", "InstanceName")))
                    {
                        x.InstanceName = Appsettings.App("Redis", "InstanceName");
                    }
                });

                services.AddTransient<IRedisCache, RedisCache>();
            }
        }
    }
}